package untils

import (
	"fmt"
	"seckill-srv/basic/config"
)

// 同步活动库存
func SyncActivityStock(activityId, stock int) error {
	key := fmt.Sprintf("seckillId:%d", activityId)
	for i := 0; i < stock; i++ {
		config.Rdb.LPush(config.Ctx, key, i+1)
	}
	return nil
}

// 获取活动库存
func GetActivityStock(activityId int) int {
	key := fmt.Sprintf("seckillId:%d", activityId)
	stock, err := config.Rdb.LLen(config.Ctx, key).Result()
	if err != nil {
		return 0
	}
	return int(stock)
}

// 扣减活动库存
func DeleteActivityStock(activityId int, num int) bool {
	key := fmt.Sprintf("seckillId:%d", activityId)
	for i := 0; i < num; i++ {
		_, err := config.Rdb.LPop(config.Ctx, key).Result()
		if err != nil {
			return false
		}
	}
	return true
}

// 回复活动库存
func ReturnActivityStock(activityId, stock int) bool {
	key := fmt.Sprintf("seckillId:%d", activityId)
	for i := 0; i < stock; i++ {
		config.Rdb.LPush(config.Ctx, key, 1)
	}
	return true
}
